package cn.cxyxj.code_auth_jwt_persistence_prod.auth.handler;

import cn.cxyxj.code_auth_jwt_persistence_prod.common.ApiResult;
import cn.cxyxj.code_auth_jwt_persistence_prod.common.ApiResultEnum;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 匿名用户(未认证)访问认证资源异常回调，默认实现类为 LoginUrlAuthenticationEntryPoint，重定向到登录页面
 */
public class CustomizeAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
        resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
        PrintWriter out = resp.getWriter();
        out.write(JSONObject.toJSONString(ApiResult.fail(ApiResultEnum.UNAUTHORIZED_ERROR)));
        out.flush();
        out.close();
    }
}
